﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using InTheHand.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Storage.Streams;

namespace WpfBluetooth.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class MainWindowModel : ObservableObject
    {
        /// <summary>
        /// 查找
        /// </summary>
        public ICommand SelectBluetooth { get; set; }
        public ICommand StartSendData { get; set; }
        public ICommand StopSendData { get; set; }
        /// <summary>
        /// 蓝牙列表
        /// </summary>
        private ObservableCollection<BluetoothMode> _BluetoothList;
        /// <summary>
        /// 蓝牙列表
        /// </summary>
        public ObservableCollection<BluetoothMode> BluetoothList { get => _BluetoothList; set => SetProperty(ref _BluetoothList, value); }
        /// <summary>
        /// 向ui添加蓝牙
        /// </summary>
        public Action<BluetoothMode> AddBlueTooth { get; set; }

        /// <summary>
        /// 蓝牙客户端
        /// </summary>
        BluetoothClient client { get; set; }
        /// <summary>
        /// 广播监听
        /// </summary>
        public BluetoothLEAdvertisementWatcher bluetoothLEAdvertisementWatcher { get; set; }
        /// <summary>
        /// 发布广播
        /// </summary>
        private BluetoothLEAdvertisementPublisher _publisher;
        public MainWindowModel()
        {
            client = new BluetoothClient();
            //SelectBluetooth = new AsyncRelayCommand(SelectBluetoothMethod);
            BluetoothList = new ObservableCollection<BluetoothMode>();
            SelectBluetooth = new RelayCommand(SelectBluetoothMethod);
            StartSendData = new RelayCommand(StartSendDataMethod);
            StopSendData = new RelayCommand(StopSendDataMethod);

            bluetoothLEAdvertisementWatcher = new BluetoothLEAdvertisementWatcher()
            {
                ScanningMode = BluetoothLEScanningMode.Active,
                AllowExtendedAdvertisements = true
            };
            bluetoothLEAdvertisementWatcher.Received += BluetoothLEAdvertisementWatcher_Received;
            bluetoothLEAdvertisementWatcher.Start();
        }
        private void BluetoothLEAdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            var data = args.Advertisement.DataSections;
            foreach (var section in data)
            {
                Console.WriteLine(section.ToString());
            }
        }
        private void StopSendDataMethod()
        {
            _publisher?.Stop();
        }

        private void StartSendDataMethod()
        {

            // 3. 创建发布者并传入广告数据
            _publisher = new BluetoothLEAdvertisementPublisher();
            // 1. 创建广播数据对象（替代直接访问.Advertisement属性）
            var advertisement = new BluetoothLEAdvertisement();
           var d=  _publisher.Advertisement.ManufacturerData;
            // 2. 配置广播数据
            ConfigureAdvertisement(advertisement);

         
            // 4. 注册状态变化事件
            _publisher.StatusChanged += _publisher_StatusChanged;

            // 5. 开始广播
            _publisher.Start();
            Console.WriteLine("BLE广播已启动...");
        }
        private void ConfigureAdvertisement(BluetoothLEAdvertisement advertisement)
        {
           
            // 设置广播参数
            advertisement.Flags = BluetoothLEAdvertisementFlags.GeneralDiscoverableMode;

            // 添加制造商数据
            var manufacturerData = new BluetoothLEManufacturerData
            {
                CompanyId = 0x1234, // 替换为您的制造商ID
                Data = CreateBufferFromString("Hello BLE")
            };
            advertisement.ManufacturerData.Add(manufacturerData);

            // 可选：添加服务UUID
            advertisement.ServiceUuids.Add(new Guid("0000ABCD-0000-1000-8000-00805F9B34FB"));
        }
        private void _publisher_StatusChanged(BluetoothLEAdvertisementPublisher sender, BluetoothLEAdvertisementPublisherStatusChangedEventArgs args)
        {
            Console.WriteLine($"广播状态变化: {args.Status}");

            if (args.Status == BluetoothLEAdvertisementPublisherStatus.Stopped)
            {
                Console.WriteLine($"停止原因: {args.Error}");
            }
        }

        private IBuffer CreateBufferFromString(string data)
        {
            var writer = new DataWriter();
            writer.WriteString(data);
            return writer.DetachBuffer();
        }
        /// <summary>
        /// 广播参数
        /// </summary>
        private void ConfigureAdvertisement()
        {
            // 设置广播间隔 (Windows 默认约100ms)
            _publisher.Advertisement.Flags = BluetoothLEAdvertisementFlags.GeneralDiscoverableMode;

            // 添加自定义制造商数据 (重要：这是广播数据的核心方式)
            var manufacturerData = new BluetoothLEManufacturerData
            {
                // 制造商ID (示例: 0x1234)
                CompanyId = 0x1234,

                // 自定义数据 (示例: "Hello BLE")
                Data = CreateBufferFromString("Hello BLE")
            };

            _publisher.Advertisement.ManufacturerData.Add(manufacturerData);
            // 可选：添加服务UUID
            _publisher.Advertisement.ServiceUuids.Add(new Guid("d175400a-9702-470c-a5e1-a26319c85bdd"));
        }

        private void SelectBluetoothMethod()
        {
            BluetoothList.Clear();
            Task.Factory.StartNew(() =>
            {
                var devices = client.DiscoverDevices();
                foreach (BluetoothDeviceInfo d in devices)
                {
                    BluetoothMode bluetoothMode = new BluetoothMode();
                    bluetoothMode.name = d.DeviceName;
                    bluetoothMode.bluetoothDeviceInfo = d;
                    bluetoothMode.client=client;
                    AddBlueTooth?.Invoke(bluetoothMode);
                }
            });
        }
    }
}
